/**
 * Markdown 相关方法
 */

const renderer = new marked.Renderer();

/**
 * 代码块支持公式、流程图、时序图
 */
renderer.code = function(code, lang, escaped) {
  if (lang === "seq" || lang === "sequence") {
    return `<div class="markdown-body-sequence-diagram">${code}</div>`;
  } else if ( lang === "flow") {
    return `<div class="markdown-body-flowchart">${code}</div>`;
  } else {
    return marked.Renderer.prototype.code.apply(this, arguments);
  }
};

/**
 * 行内公式、整行公式
 */
renderer.paragraph = function(text) {
  let isTeXInline     = /\$(.*)\$/g.test(text);
  let isTeXLine       = /^\$\$(.*)\$\$$/.test(text);
  let isPageBreak     = /^\[[=]{8,}\]$/.test(text);

  if (isTeXLine) {
    // 整行公式
    text = text.replace(/(\$\$([^\$]*)\$\$)+/g, function($1, $2) {
      return `<p class="markdown-body-math">${$2.replace(/\$/g, "")}</p>`;
    });
  } else if (isTeXInline) {
    // 行内公式
    text = text.replace(/(\$([^\$]*)\$)+/g, function($1, $2) {
      return `<span class="markdown-body-math">${$2.replace(/\$/g, "")}</span>`;
    });
  } else if(isPageBreak) {
    // 分页
    text = "\r\n[========]\r\n";
  } else {
    // 普通段落
    text = `<p>${text}</p>`;
  }

  return text;
};

marked.setOptions({
  highlight: function(code) {
    return hljs.highlightAuto(code).value;
  },
  renderer: renderer,
  gfm: true,
  tables: true,
  breaks: true,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false
});

export default {
  /**
   * markdown 渲染成 HTML
   * @param markdown
   */
  render: (markdown) => {
    return marked(markdown);
  }
}